package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"stu.stdx.com/src/config"
	"stu.stdx.com/src/login"
	"stu.stdx.com/src/stu"
)

func main() {

	// TODO: Add your code here
	// 设置日志输出到文件
	logFile, err := os.OpenFile("./log/custom.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("Failed to open log file: %v", err)
		return
	}
	defer logFile.Close()

	// 设置日志输出到文件
	log.SetOutput(logFile)

	// 读取配置
	cfg, err := config.LoadConfig("config.yaml")
	if err != nil {
		fmt.Println("读取配置文件失败", err)
		return
	}
	// 配置用户登录信息
	user := login.LoginUser{
		AdminName:     cfg.User.AdminName,
		AdminPassword: cfg.User.AdminPassword,
		SorT:          cfg.User.SorT,
	}
	fmt.Println(user)
	// 创建http客户端
	client := &http.Client{
		Transport: &http.Transport{
			DisableKeepAlives: true, // 关闭长连接
		},
		Jar: login.LoadCookies(),
	}

	if !login.CheckLogin(client) {
		if err := login.Login(client, &user); err != nil {
			log.Fatalf("Login failed: %v", err)
			return
		}
		err := login.SaveCookies(client)
		if err != nil {
			log.Fatalf("Failed to save cookies: %v", err)
			return
		}
	}
	client.Jar = login.LoadCookies()

	fmt.Println("登录完成")
	fmt.Println("==================开始课程获取==================")

	courseType := cfg.Course.CourseType
	var courseMap map[string]stu.StuCourse
	//var cErr error

	if courseType == 2 {
		coursePageURL := cfg.Course.Live.Url + "?kcdm=" + cfg.Course.Live.Kcdm
		courseMap, _ = stu.FetchPageListLive(client, coursePageURL)
	} else {
		coursePageURL := cfg.Course.Shiping.Url + "?kcdm=" + cfg.Course.Shiping.Kcdm
		courseMap, _ = stu.FetchPageListNonLive(client, coursePageURL)
	}

	// 1.创建任务队列
	queue := stu.NewTaskQueue()
	// 2.设置任务队列等待时间
	//queue.SetWaitTime(2)/
	var taskLists []stu.VideoTask
	// 3.创建任务
	for _, value := range courseMap {
		videoinfo, _ := stu.GetVideoInfo(client, value, cfg.Socket)
		if !videoinfo.Completed {
			fmt.Println("正在获取视频信息", videoinfo)
			taskLists = append(taskLists, videoinfo)
		}
	}

	if len(taskLists) == 0 {
		fmt.Println("没有需要的课程")
		return
	}
	// 4.添加任务到队列
	queue.AddTasks(taskLists)

	// 5.执行任务
	queue.ExecuteTasks()

	fmt.Println("\n[INFO] Program terminated, closing WebSocket.")
	fmt.Println("==================所有课程已完成==================")

}
